package com.fengye.redisson.demo.lock;

import com.fengye.redisson.demo.dto.BookDTO;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * 可重入锁实现商品抢购
 * @author sky
 * @date 2021年06月16日 1:17 下午
 */
@Service
@Slf4j
public class RobService {
    @Autowired
    private RedissonClient client;


    /**
     * 商品抢购逻辑
     */
    @Transactional(rollbackFor = Exception.class)
    public void RobBookWithRedisson(BookDTO dto) {
        final String lockName = "redissonTryLock" + dto.getBookNo() + "-" + dto.getUserId();

        RLock lock = client.getLock(lockName);

        try {
            boolean result = lock.tryLock(100, 10, TimeUnit.SECONDS);
            if (result) {
                log.info("获取分布式锁。。。开始执行抢购逻辑");

            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}
